package org.jeecg.modules.tz.controller;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.service.ISysAnnouncementService;
import org.jeecg.modules.system.udp.UdpServer;
import org.jeecg.modules.tz.entity.TzNetwork;
import org.jeecg.modules.tz.entity.TzNetworkItem;
import org.jeecg.modules.tz.service.ITzNetworkItemService;
import org.jeecg.modules.tz.service.ITzNetworkService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.tz.service.ITzThirdService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.expression.Expression;
import org.springframework.integration.ip.udp.UnicastSendingMessageHandler;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: tz_network
 * @Author: jeecg-boot
 * @Date:   2024-08-26
 * @Version: V1.0
 */
@Api(tags="tz_network")
@RestController
@RequestMapping("/tz/tzNetwork")
@Slf4j
public class TzNetworkController extends JeecgController<TzNetwork, ITzNetworkService> {
	 private static final Logger logger = LoggerFactory.getLogger(TzNetworkController.class);

	 @Autowired
	 private ITzNetworkService tzNetworkService;
	 @Autowired
	 private ITzNetworkItemService tzNetworkItemService;
	 @Autowired
	 private ISysAnnouncementService sysAnnouncementService;
	 @Autowired
	 private ITzThirdService tzThirdService;

	 @Value("${udp.sendingPort}")
	 public Integer sendingPort;

	 @Value("${udp.sendingIp}")
	 public String sendingIp;

	 @PostMapping(value = "/sync")
	 public Result<String> sync() {
		 boolean b = tzThirdService.machinePortList();
		 if(!b){
			 return Result.error("同步失败");
		 }else{
			 return Result.ok("同步成功");
		 }
	 }



	 @PostMapping(value = "/machinePortList")
	 public Result<List> machinePortList() {
	 	 List list = new ArrayList();
	 	 Map<String,Object> map = new HashMap<>();
	 	 map.put("name","xxxx");
	 	 map.put("jpomUrl","192.168.136.10:2123");
	 	 map.put("id","1001");
		 List list_ip = new ArrayList();
		 for(int i = 0;i<49;i++){
			 list_ip.add("192.168.136."+i);
		 }
//		 list_ip.add("192.168.136.101");
//		 list_ip.add("192.168.136.102");
		 Map<String,Object> map_port = new HashMap<>();
		 map_port.put("8089",list_ip);
//		 map_port.put("80",list_ip);
	 	 map.put("ports",map_port);

		 list.add(map);
		 return Result.ok(list);
	 }
	 @PostMapping(value = "/notifyLog")
	 public void notifyLog(@RequestBody JSONObject jsonObject) {
		 System.out.println("title:"+jsonObject.getString("title")+",content"+jsonObject.getString("content"));
	 }


	/**
	 * 分页列表查询
	 *
	 * @param tzNetwork
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "tz_network-分页列表查询")
	@ApiOperation(value="tz_network-分页列表查询", notes="tz_network-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TzNetwork>> queryPageList(TzNetwork tzNetwork,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TzNetwork> queryWrapper = QueryGenerator.initQueryWrapper(tzNetwork, req.getParameterMap());
		Page<TzNetwork> page = new Page<TzNetwork>(pageNo, pageSize);
		IPage<TzNetwork> pageList = tzNetworkService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 //首页汇总信息
	 @GetMapping(value = "/analyse")
	 public Result<Map<String, Object>> analyse() {
		 Map<String, Object> total = new HashMap<>();
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String userId = sysUser.getId();
		 List<Map<String, String>> analyse_day = sysAnnouncementService.analyse_day(userId);//告警智能分类分析(过去7天)//七天之前的需要清除

		 List<Map<String, String>> analyse_type = sysAnnouncementService.analyse_type(userId);//告警智能分类分析(过去7天)
		 long tzNetworkCount = tzNetworkService.count();//业务服务器总数
		 long tzNetworkItemCount = tzNetworkItemService.count();//关键业务节点总数
		 long sysAnnouncementCount = sysAnnouncementService.count();//异常告警数量
		 List<Map<String, String>> maps = tzNetworkItemService.analyse_proto();//协议分布

		 total.put("tzNetworkCount",tzNetworkCount);
		 total.put("tzNetworkItemCount",tzNetworkItemCount);
		 total.put("sysAnnouncementCount",sysAnnouncementCount);
		 total.put("maps",maps);
		 total.put("analyse_day",analyse_day);
		 total.put("analyse_type",analyse_type);
		 return Result.ok(total);
	 }


	 @ApiOperation(value="tz_network-分页列表查询", notes="tz_network-分页列表查询")
	 @GetMapping(value = "/graph")
	 public Result<List<TzNetwork>> graph() {
//		 LambdaQueryWrapper<TzNetwork> queryWrapper = new LambdaQueryWrapper<>();
//
//		 List<TzNetwork> list = tzNetworkService.list(queryWrapper);
//
//		 list.forEach(e->{
//			 LambdaQueryWrapper<TzNetworkItem> queryWrapper_item = new LambdaQueryWrapper<>();
//			 queryWrapper_item.eq(TzNetworkItem::getNetworkId,e.getId());
//			 List<TzNetworkItem> list1 = tzNetworkItemService.list(queryWrapper_item);
//			 e.setTzNetworkItems(list1);
//		 });
		 List<TzNetwork> tzNetworks = tzNetworkService.listAllNetWork();
		 return Result.OK(tzNetworks);
	 }
	
	/**
	 *   添加
	 *
	 * @param tzNetwork
	 * @return
	 */
	@AutoLog(value = "tz_network-添加")
	@ApiOperation(value="tz_network-添加", notes="tz_network-添加")
	//@RequiresPermissions("org.jeecg.modules:tz_network:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TzNetwork tzNetwork) {
		tzNetwork.setStatus(0);
		tzNetworkService.save(tzNetwork);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param tzNetwork
	 * @return
	 */
	@AutoLog(value = "tz_network-编辑")
	@ApiOperation(value="tz_network-编辑", notes="tz_network-编辑")
	//@RequiresPermissions("org.jeecg.modules:tz_network:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody TzNetwork tzNetwork) {
		tzNetworkService.updateById(tzNetwork);
		return Result.OK("编辑成功!");
	}

	 /**
	  *  生成配置文件且下发给代理
	  *
	  *  <net>
		  * freq=10
		  * my_ip = 192.168.136.13
		  * my_port = 8888
		  * serv_ip = 192.168.136.1
		  * serv_port = 9999
		  * serv_cnt = 2
		  * local_ip1 = 192.168.136.13
		  * local_port1= 2000
		  * local_proto1= udp
		  * across_ip1= 192.168.136.13
		  * across_port1 = 2002
		  * local_ip2 = 192.168.136.13
		  * local_port2 = 2001
		  * local_proto2 = tcp
		  * across_ip2 = 192.168.136.1
		  * across_port2 = 2003
	  * </net>
	  *  tcpdump -i ens33  port 8888
	  *  tcpdump -i ens33 host 192.168.136.10 and dst  port 8888
	  * @param tzNetwork
	  * @return
	  */
	 @AutoLog(value = "tz_network-生成配置文件")
	 @ApiOperation(value="tz_network-生成配置文件", notes="tz_network-生成配置文件")
	 //@RequiresPermissions("org.jeecg.modules:tz_network:edit")
	 @RequestMapping(value = "/genConfig", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> genConfig(@RequestBody TzNetwork tzNetwork) throws IOException {
//		 tzNetworkService.updateById(tzNetwork);
		 TzNetwork tzNetworkConfig = tzNetworkService.listNetWorkById(tzNetwork.getId());
		 List<TzNetworkItem> tzNetworkItems = tzNetworkConfig.getTzNetworkItems();
		 //创建临时文件
		 File netFile = File.createTempFile("net", ".ini");//创建临时文件
		 logger.info("临时文件所在的本地路径：" + netFile.getCanonicalPath());
		 BufferedWriter fileWritter = new BufferedWriter(new FileWriter(netFile.getAbsolutePath()));
		 StringBuffer data = new StringBuffer();
		 fileWritter.write("<net>");
		 fileWritter.newLine();

		 fileWritter.write("freq = " + tzNetworkConfig.getFreq());
		 fileWritter.newLine();

		 fileWritter.write("my_ip = " + tzNetworkConfig.getTzIp());
		 fileWritter.newLine();

		 fileWritter.write("my_port = " + tzNetworkConfig.getMyPort());
		 fileWritter.newLine();

		 fileWritter.write("serv_ip = " + tzNetworkConfig.getServIp());
		 fileWritter.newLine();

		 fileWritter.write("serv_port = " + tzNetworkConfig.getServPort());
		 fileWritter.newLine();

		 fileWritter.write("serv_cnt = " + tzNetworkItems.size());
		 fileWritter.newLine();
		 for (int i = 0; i < tzNetworkItems.size(); i++) {
			 TzNetworkItem tzNetworkItem = tzNetworkItems.get(i);
			 fileWritter.write("local_ip"+ (i+1) + " = " + tzNetworkItem.getLocalIp());
			 fileWritter.newLine();

			 fileWritter.write("local_port"+ (i+1) + " = " + tzNetworkItem.getLocalPort());
			 fileWritter.newLine();

			 fileWritter.write("local_proto"+ (i+1) + " = " + tzNetworkItem.getLocalProto());
			 fileWritter.newLine();

			 fileWritter.write("across_ip"+ (i+1) + " = " + tzNetworkItem.getAcrossIp());
			 fileWritter.newLine();

			 fileWritter.write("across_port"+ (i+1) + " = " + tzNetworkItem.getAcrossPort());
			 fileWritter.newLine();
		 }

		 fileWritter.write("</net>");
		 fileWritter.newLine();

		 fileWritter.flush();
		 fileWritter.close();

		 FileInputStream fis = new FileInputStream(netFile);
		 byte[] buffer = new byte[(int) netFile.length()];
		 fis.read(buffer);
		 fis.close();

		 // 创建UDP发送消息处理器
		 UnicastSendingMessageHandler sendingMessageHandler = new UnicastSendingMessageHandler(tzNetworkConfig.getTzIp(), Integer.valueOf(tzNetworkConfig.getMyPort()));
//		 UnicastSendingMessageHandler sendingMessageHandler = new UnicastSendingMessageHandler("192.168.2.70", 1234);
		 // 启动消息处理器
		 sendingMessageHandler.start();
		 // 将文件字节数组作为消息发送
		 sendingMessageHandler.handleMessage(MessageBuilder.withPayload(buffer).build());
		 // 停止消息处理器
		 sendingMessageHandler.stop();
		 System.out.println("发送主机：" + tzNetworkConfig.getTzIp());
		 System.out.println("端口" + Integer.valueOf(tzNetworkConfig.getMyPort()));
		 logger.info("发送成功");
//		 fileWritter.write(data.toString());
		 return Result.OK("配置文件下发成功!");
	 }

	 @AutoLog(value = "tz_network-批量生成配置文件")
	 @ApiOperation(value="tz_network-批量生成配置文件", notes="tz_network-批量生成配置文件")
	 //@RequiresPermissions("org.jeecg.modules:tz_network:edit")
	 @RequestMapping(value = "/genMultiConfig", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> genMultiConfig() throws IOException {
		 List<TzNetwork> tzNetworks = tzNetworkService.listAllNetWork();
		 for(TzNetwork tzNetworkConfig:tzNetworks){
//			 TzNetwork tzNetworkConfig = tzNetworkService.listNetWorkById(tzNetwork.getId());
			 List<TzNetworkItem> tzNetworkItems = tzNetworkConfig.getTzNetworkItems();
			 //创建临时文件
			 File netFile = File.createTempFile("net", ".ini");//创建临时文件
			 logger.info("临时文件所在的本地路径：" + netFile.getCanonicalPath());
			 BufferedWriter fileWritter = new BufferedWriter(new FileWriter(netFile.getAbsolutePath()));
			 StringBuffer data = new StringBuffer();
			 fileWritter.write("<net>");
			 fileWritter.newLine();

			 fileWritter.write("freq = " + tzNetworkConfig.getFreq());
			 fileWritter.newLine();

			 fileWritter.write("my_ip = " + tzNetworkConfig.getTzIp());
			 fileWritter.newLine();

			 fileWritter.write("my_port = " + tzNetworkConfig.getMyPort());
			 fileWritter.newLine();

			 fileWritter.write("serv_ip = " + tzNetworkConfig.getServIp());
			 fileWritter.newLine();

			 fileWritter.write("serv_port = " + tzNetworkConfig.getServPort());
			 fileWritter.newLine();

			 fileWritter.write("serv_cnt = " + tzNetworkItems.size());
			 fileWritter.newLine();
			 for (int i = 0; i < tzNetworkItems.size(); i++) {
				 TzNetworkItem tzNetworkItem = tzNetworkItems.get(i);
				 fileWritter.write("local_ip"+ (i+1) + " = " + tzNetworkItem.getLocalIp());
				 fileWritter.newLine();

				 fileWritter.write("local_port"+ (i+1) + " = " + tzNetworkItem.getLocalPort());
				 fileWritter.newLine();

				 fileWritter.write("local_proto"+ (i+1) + " = " + tzNetworkItem.getLocalProto());
				 fileWritter.newLine();

				 fileWritter.write("across_ip"+ (i+1) + " = " + tzNetworkItem.getAcrossIp());
				 fileWritter.newLine();

				 fileWritter.write("across_port"+ (i+1) + " = " + tzNetworkItem.getAcrossPort());
				 fileWritter.newLine();
			 }

			 fileWritter.write("</net>");
			 fileWritter.newLine();

			 fileWritter.flush();
			 fileWritter.close();

			 FileInputStream fis = new FileInputStream(netFile);
			 byte[] buffer = new byte[(int) netFile.length()];
			 fis.read(buffer);
			 fis.close();

			 // 创建UDP发送消息处理器
			 UnicastSendingMessageHandler sendingMessageHandler = new UnicastSendingMessageHandler(tzNetworkConfig.getTzIp(), Integer.valueOf(tzNetworkConfig.getMyPort()));
			 // 启动消息处理器
			 sendingMessageHandler.start();
			 // 将文件字节数组作为消息发送
			 sendingMessageHandler.handleMessage(MessageBuilder.withPayload(buffer).build());
			 // 停止消息处理器
			 sendingMessageHandler.stop();
		 }
		 logger.info("发送成功");
		 return Result.OK("配置文件下发成功!");
	 }
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "tz_network-通过id删除")
	@ApiOperation(value="tz_network-通过id删除", notes="tz_network-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:tz_network:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		//首先删除配置信息
		LambdaQueryWrapper<TzNetworkItem> query = new LambdaQueryWrapper<>();
		query.eq(TzNetworkItem::getNetworkId,id);
		tzNetworkItemService.remove(query);
		tzNetworkService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "tz_network-批量删除")
	@ApiOperation(value="tz_network-批量删除", notes="tz_network-批量删除")
	//@RequiresPermissions("org.jeecg.modules:tz_network:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tzNetworkService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "tz_network-通过id查询")
	@ApiOperation(value="tz_network-通过id查询", notes="tz_network-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TzNetwork> queryById(@RequestParam(name="id",required=true) String id) {
		TzNetwork tzNetwork = tzNetworkService.getById(id);
		if(tzNetwork==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tzNetwork);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tzNetwork
    */
    //@RequiresPermissions("org.jeecg.modules:tz_network:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TzNetwork tzNetwork) {
        return super.exportXls(request, tzNetwork, TzNetwork.class, "tz_network");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("tz_network:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TzNetwork.class);
    }

}
